<script setup>
  import { ref, watch, computed } from 'vue'

  // 导入 css
  import './assets/style.css'

  // 导入对应的组件
  import TodoHeader from './components/TodoHeader.vue';
  import TodoMain from './components/TodoMain.vue';
  import TodoFooter from './components/TodoFooter.vue';

  const DEFAULT_TODOLIST = [
    { id: 321, name: '学Vue组件通信', finished: false },
    { id: 127, name: '打王者', finished: true },
    { id: 666, name: '跑步1⼩时', finished: false }
  ]
  const KEY_TODOLIST = 'key-todo-list' // todoList 存储到本地的名称

  // 任务列表
  const todoList = ref(
    JSON.parse(localStorage.getItem(KEY_TODOLIST)) || DEFAULT_TODOLIST
  )

  // 添加功能
  const add = (name) => {
    todoList.value.push({
      id: Date.now(),
      name,
      finished: false
    })
  }

  // 删除功能
  const delTodo = (index) => {
    !window.confirm('确认要删除么？') || todoList.value.splice(index, 1)
  }

  // 统计未完成的个数 采用计算属性
  const todoCount = computed(() => {
    return todoList.value.filter((v) => !v.finished).length
  })

  // 清除已经完成的
  const clearCompleted = () => {
    if (confirm('确认要清除已完成的吗？')) {
      todoList.value = todoList.value.filter((v) => !v.finished)
    }
  }

  // 监听 todoList 每次修改都要存储到本地
  watch(todoList, (newVal) => {
    // 存储到本地
    localStorage.setItem(KEY_TODOLIST, JSON.stringify(todoList.value))
  }, {
    // 开启深度监听
    deep: true
  })
</script>

<template>
  <div class="todoapp">
    <todo-header @add-item="add" />
    <todo-main
      :todoList="todoList"
      @del-todo="delTodo"
    />
    <todo-footer
      :todoCount="todoCount"
      @clear-completed="clearCompleted"
    />
  </div>
</template>


<style scoped></style>